package com.sun.tv;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.util.EntityUtils;

import android.app.Service;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Handler;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;

import com.tools.Base64;
import com.tools.HttpInterface;
import com.tools.HttpThrowable;
import com.tools.MyLog;
import com.tools.SysInterfacePhone;
import com.tools.UserLocation;

public final class TVAdManage {
	public static TVAdManage admanage;
	public static SDKData sdkData;
	
	public Handler handler;
	private AdConfig config;
	private Base64 base64 = new Base64();
	private TVAdManage(Context context){
		sdkData = new SDKData();
		sdkData.checkPermisions(context);
	}
	public static TVAdManage getManage(Context context){
		return new TVAdManage(context);
	}
	public Map<String, WeakReference<TVAdView>> adViewWindowMap = new HashMap<String, WeakReference<TVAdView>>();
	public void pubAdViewWindow(String key, TVAdView adView) {
		adViewWindowMap.put(key, new WeakReference<TVAdView>(adView));
		key = null;
	}
	public  WeakReference<TVAdView> getAdView(String key){
		return adViewWindowMap.get(key);
	}
	synchronized AdConfig fetchConfig(String key) {
		MyLog.v("called fetchConfig");
		config = null;
		String url = "";
		WeakReference<TVAdView> weakAdViewWindow = adViewWindowMap.get(key);
		MyLog.v("weakAdViewWindow-->" + weakAdViewWindow);
		if (weakAdViewWindow == null) {
			MyLog.e("weakAdViewWindow is null");
			return null;
		}
		TVAdView adviewWindow;
		adviewWindow = (TVAdView) weakAdViewWindow.get();
		MyLog.v("adviewWindow-->" + adviewWindow);
		if (adviewWindow == null) {
			MyLog.e(new HttpThrowable(HttpThrowable.UNKOWN_ERROR,
					"HdtMobileAdViewWindow is null"));
			return null;
		}
		MyLog.v("IMochaEventCode.startDownloadAd-->"
				+ IMochaEventCode.startDownloadAd);
		adviewWindow.onEvent(IMochaEventCode.startDownloadAd);
		Context context = adviewWindow.contextWeakReference.get();
		if (context == null) {
			MyLog.e("activity is null");
			return null;
		}
		url = getParameterUrl(context, adviewWindow);// 得到带有请求参数的URL
		if (url == null) {
			MyLog.e("parameter url is error");
			return null;
		}
		url = sdkData.getServerUrl(adviewWindow.serverId)+url;
		
		HttpInterface httpInterface = new HttpInterface(handler);
		HttpEntity entity = null;
		// http://122.225.32.34:8088/p/?pid=4540&guid=8bda4ced08eb6a8d&os=1&osv=2.1-update1&sdkv=A2.353&scrn-w=480&scrn-h=854&sub-id=10000&funcs=vtgscw&ua=XT702&imei=MTMzNjM1OTIwMDM0Mw%3D%3D&package=com.imocha&appvc=2353&appvn=1.0
		try {
			entity = httpInterface.httpGetConnection(
					httpInterface.createHttpClient(20), url);
		} catch (HttpThrowable e) {
			if (e.errorCode == HttpThrowable.INTENT_ERROR) {
				adviewWindow.onEvent(IMochaEventCode.networkError);
			} else if (e.errorCode == HttpThrowable.STATUS_CODE_ERROR) {
				adviewWindow.onEvent(IMochaEventCode.networkError);
			} else {
				adviewWindow.onEvent(IMochaEventCode.downloadError);
			}
			e.printStackTrace();
			return null;
		}

		if (entity == null) {
			MyLog.e("entity is null,\n please check intet");
			config = null;
			return config;
		}

		try {
			String xml;
			xml = new String(EntityUtils.toByteArray(entity));
			if (xml == null || xml.length() < 10) {
				adviewWindow.onEvent(IMochaEventCode.noAd);
				return null;
			}
			MyLog.d("xml = " + xml);
			entity.consumeContent();// 释放该实体(HttpEntity)的内容
			resolveXML(xml, key);// 解析XML
		} catch (Exception e1) {
			adviewWindow.onEvent(IMochaEventCode.parseError);
			e1.printStackTrace();
		}
		if (config == null) {
			adviewWindow.onEvent(IMochaEventCode.downloadError);
			return null;
		}

		return config;
	}

	private AdConfig resolveXML(String xml, String key) throws Exception {
		WeakReference<TVAdView> weakAdViewWindow = adViewWindowMap.get(key);

		if (weakAdViewWindow == null) {
			MyLog.e("weakAdViewWindow is null");
			return null;
		}
		TVAdView adviewWindow;
		adviewWindow = (TVAdView) weakAdViewWindow.get();
		if (adviewWindow == null) {
			MyLog.e(new HttpThrowable(HttpThrowable.UNKOWN_ERROR,
					"HdtMobileAdViewWindow is null"));
			return null;
		}
		Context context = adviewWindow.contextWeakReference.get();
		if (context == null) {
			MyLog.e(new HttpThrowable(HttpThrowable.UNKOWN_ERROR,
					"HdtMobileAdViewWindow is null"));
			return null;
		}
		return null;
	}

	synchronized void downloadRes(String key, AdConfig tempConfig) throws HttpThrowable {
		if (tempConfig == null) {
			throw new HttpThrowable(HttpThrowable.UNKOWN_ERROR,
					"HdtMobileAdViewWindow is null");
		}
		WeakReference<TVAdView> weakAdViewWindow = adViewWindowMap.get(key);
		if (weakAdViewWindow == null) {
			throw new HttpThrowable(HttpThrowable.UNKOWN_ERROR,
					"weakAdViewWindow is null");
		}
		TVAdView adviewWindow =  weakAdViewWindow.get();
		if (adviewWindow == null) {
			throw new HttpThrowable(HttpThrowable.UNKOWN_ERROR,
					"HdtMobileAdViewWindow is null");
		}
		// MyLog.v("start download res ,the ad type is " + adviewWindow.adType +
		// " the ad hashcode:" + key);
		Context context = adviewWindow.contextWeakReference.get();
		if (context == null) {
			throw new HttpThrowable(HttpThrowable.UNKOWN_ERROR,
					"activity is null");
		}
		String url = tempConfig.getResUrl();
		if (url == null) {
			throw new HttpThrowable(HttpThrowable.UNKOWN_ERROR,
					"download res of url is null");
		}
		MyLog.v("aaron.ResUrl = " + url);
		//根据url判断资源包是否是有效的广告资源类型
		if (!url.endsWith(".html.zip") && !url.endsWith(".gif")
				&& !url.endsWith(ContentType.LOCALWAP_HTML_ZIP)
				&& !url.endsWith(ContentType.LOCALWAP_IMAGE_ZIP)) {
			throw new HttpThrowable(HttpThrowable.UNKOWN_ERROR,
					"Resources format error!");
		}
		if (config.hasAd(key)) {
			/*------ ran.huang 2012-12-18 上午11:32:13 add start ------*/
			if (config.resType == AdConfig.ResType.Html) {
//				config.getHtmlType(activity);
			}
			/*------ ran.huang 2012-12-18 上午11:32:18 add end ------*/
			adviewWindow.onEvent(IMochaEventCode.hasRes);
			return;
		}
		adviewWindow.onEvent(IMochaEventCode.noRes);

		adviewWindow.onEvent(IMochaEventCode.downloadRes);

		HttpInterface httpInterface = new HttpInterface(handler);

		HttpClient httpClient = httpInterface.createHttpClient(20);

		// 请求HTTP头，查看文件的大不
		HttpHead httphead = new HttpHead(config.getResUrl());
		HttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httphead);
		} catch (Exception e1) {
			throw new HttpThrowable(HttpThrowable.INTENT_ERROR, e1);
		}
		int code = httpResponse.getStatusLine().getStatusCode();
		if (code != 200) {
			if (code == 404) {
				IMochaEventCode errorCode = IMochaEventCode.unknown;
				errorCode.setValue("资源未找到.");
				adviewWindow.onEvent(errorCode);
			} else
				throw new HttpThrowable(HttpThrowable.INTENT_ERROR,
						"download res head,the response code :"
								+ httpResponse.getStatusLine().getStatusCode());
		}
		Header[] headers = httpResponse.getHeaders("Content-Length");
		if (headers == null || headers.length < 1) {
			adviewWindow.onEvent(IMochaEventCode.noAd);
		} else {
			long contentSize = Long.parseLong(headers[0].getValue());
			MyLog.v("download res,res size:" + contentSize);
			if (!config.preferences.isEnoughMemory(contentSize)) {// 本地缓存是否够用(10M)。
				throw new HttpThrowable(HttpThrowable.UNKOWN_ERROR,
						"Memory is not enough");
			}
		}

		HttpEntity entity = null;

		try {
			entity = httpInterface.httpGetConnection(
					httpInterface.createHttpClient(20), url);
		} catch (HttpThrowable e) {
			if (e.errorCode == HttpThrowable.INTENT_ERROR) {
				adviewWindow.onEvent(IMochaEventCode.networkError);
			} else if (e.errorCode == HttpThrowable.STATUS_CODE_ERROR) {
				adviewWindow.onEvent(IMochaEventCode.networkError);
			} else {
				adviewWindow.onEvent(IMochaEventCode.downloadError);
			}
			throw (e);
		}

		if (entity != null) {
			byte[] bytes = null;
			try {
				bytes = EntityUtils.toByteArray(entity);
			} catch (IOException e) {
				throw new HttpThrowable(HttpThrowable.DOWNLOAD_ERROR,
						" Entity to byte fail");
			}
			if (bytes.length > 2) {
				config.bytes = bytes;
				if (!config.saveAd(key)) {
					config = null;
					throw new HttpThrowable(HttpThrowable.UNKOWN_ERROR,
							"save ad fail");//
				}
			} else {
				throw new HttpThrowable(HttpThrowable.DOWNLOAD_ERROR,
						"download res fail");//
			}
		}

	}

	@SuppressWarnings("finally")
	private String getParameterUrl(Context context, TVAdView adViewWindow) {
		StringBuffer parameterUrl = new StringBuffer();
		try {
			parameterUrl.append("pid=" + adViewWindow.spaceId);
			parameterUrl.append("&guid="
					+ SysInterfacePhone.invoker().getGUID(context));
			// 添加平台信息
			parameterUrl.append("&os=1");
			// 添加平台版本
			String version = SysInterfacePhone.invoker().getCurrentSdkVersion();

			try {
				if (version.length() > 20) {
					version = version.substring(0, 20);
				}
				parameterUrl.append("&osv="
						+ URLEncoder.encode(new String(version.getBytes(),
								"UTF-8"), "UTF-8"));
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
			parameterUrl.append("&sdkv=" + SysInterfacePhone.SDKVIS);
			// 添加屏幕宽高
			parameterUrl.append("&scrn-w="
					+ SysInterfacePhone.invoker().getScreenWidth2(context));
			parameterUrl.append("&scrn-h="
					+ SysInterfacePhone.invoker().getScreenHeight2(context));
			// 添加应用ID &funcs=vtgscw&
			if (adViewWindow.subId != null && adViewWindow.subId.length() > 0) {
				parameterUrl.append("&sub-id=" + adViewWindow.subId);
			}

			parameterUrl.append("&funcs=" + "v");// video
			parameterUrl.append("t");// touchscreen
			parameterUrl.append("g");// gps
			SmsManager smsManager = SmsManager.getDefault();
			if (smsManager != null)
				parameterUrl.append("s");// sms
			// IPhone iPhone = getPhoneInterface();
			TelephonyManager iphone = (TelephonyManager) context
					.getSystemService(Service.TELEPHONY_SERVICE);
			if (iphone != null)
				parameterUrl.append("c");// call
			HttpInterface httpInterface = new HttpInterface(handler);
			parameterUrl
					.append(httpInterface.isWifiEnabled(context) ? "w" : "");// wifi
			UserLocation userLocation=new UserLocation(context, handler);
			Location location = httpInterface.getLocation(context);
			if (location != null) {
				// 添加经纬度
				double longitude = location.getLongitude();// 经度
				double latitude = location.getLatitude();// 纬度
				DecimalFormat df = new DecimalFormat("######0.0000000000");
				parameterUrl.append("&gps=" + df.format(longitude) + ","
						+ df.format(latitude));
				MyLog.i("UserLocation:location = " + longitude +"	" + latitude);
			}
			else MyLog.i("UserLocation: location is null");
			// 添加UA
			byte ua[] = SysInterfacePhone.invoker().getUA().getBytes();
			byte uas[] = null;
			if (ua.length > 32) {
				uas = new byte[32];
				System.arraycopy(ua, 0, uas, 0, uas.length);
			} else {
				uas = new byte[ua.length];
				System.arraycopy(ua, 0, uas, 0, uas.length);
			}
			parameterUrl.append("&ua="
					+ URLEncoder.encode(new String(uas, "UTF-8"), "UTF-8"));
			/*------ ran.huang 2012-12-10 下午6:04:42 update start ------*/
//			String imei = getimei(context);
			/*------ ran.huang 2012-12-10 下午6:04:42 update end ------*/
//			parameterUrl.append("&imei=" + URLEncoder.encode(imei));
			PackageInfo packageInfo = SysInterfacePhone.invoker()
					.getPackageInfo(context);
			// ResolveInfo resolveInfo = packageInfo;
			PackageManager pm = context.getPackageManager();
			// &an=HDTMobile%E6%B5%8B%E8%AF%95%E7%A8%8B%E5%BA%8F+V3.0+labe%3A6.26+19%3A30
			// &package=com.hdtmobile
			// &appvc=1
			// &appvn=1.0
			// &cn=MTM0MDc3ODgxMzU0OA%3D%3D
			// &mn=MTM0MDc3ODgxMzU0OA%3D%3D
			// &it=false
			// pm.info.activityInfo.loadLabel(getPackageManager())
			// shareItem.setLabel();
			String appname = pm
					.getApplicationLabel(packageInfo.applicationInfo)
					.toString();
			parameterUrl.append("&an=" + URLEncoder.encode(appname, "UTF-8"));// appname

			parameterUrl.append("&package=" + packageInfo.packageName);// appname
			parameterUrl.append("&appvc=" + packageInfo.versionCode);// appversionCode
			parameterUrl.append("&appvn=" + packageInfo.versionName);// android:versionName
			 TelephonyManager tm =
			(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
			String mn =  tm.getSimOperator();
			MyLog.i("mn:" + mn);
			if (mn.length() >= 5) {
				parameterUrl.append("&cn=" + mn.substring(0, 3));// 国家码

				parameterUrl.append("&mn=" + mn.substring(3, 5));// 移动网号
			} else {
				parameterUrl.append("&cn=");// 国家码

				parameterUrl.append("&mn=");// 移动网号
			}
			String mac=SysInterfacePhone.invoker().getMac(context);
			if(mac!=null) parameterUrl.append("&md=" + mac);
			// parameterUrl.append("&it=" +
			// SysInterfacePhone.invoker().isRooted());//是否root
//			12-28 15:32:50.330: W/System.err(2106): com.tools.HttpThrowable: java.net.URISyntaxException: Illegal character in query at index 245: http://qr.hdtmobile.com/p/?pid=5621&guid=4f35805a7bdb8d07&os=1&osv=4.0.4&sdkv=A3.0.1&scrn-w=480&scrn-h=854&funcs=vtgscw&ua=MI-ONE&imei=4O9DY5MzIzMDAxMjE2NDAzW3xdTUktT05FW3xdOTQ6REI6Qzk6Qzg6NTk6MEVbfF03MGYwZDliNWQwM2Q1MmEyW3xdMTM1NjY3OTk3MDMxNQ=={&an=HDTMobile%E6%B5%8B%E8%AF%95%E7%A8%8B%E5%BA%8F+V3.0.1+labe%3A12.27+14%3A05&package=com.hdtmobile&appvc=1&appvn=1.0&cn=&mn=&md=94:DB:C9:C8:59:0E
//pid=5621&guid=248bd28b78f6685f&os=1&osv=4.0.4&sdkv=A3.0.1&scrn-w=480&scrn-h=800&funcs=vtgscw&ua=Desire+S&imei=5M8zU1MDY3MDQyNjY1NDg5W3xdRGVzaXJlIFNbfF03Qzo2MTo5MzpFQzo1RjozN1t8XTdmMjZhYWNmYmRiYmM3Mlt8XTEzNTY3MDE2OTg2NzY%3D&an=HDTMobile%E6%B5%8B%E8%AF%95%E7%A8%8B%E5%BA%8F+V3.0.1+labe%3A12.28+21%3A31&package=com.hdtmobile&appvc=1&appvn=1.0&cn=460&mn=02&md=7C:61:93:EC:5F:37
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			return parameterUrl.toString();
		}
	}

	/*------ ran.huang 2012-12-10 下午6:03:46 add start ------*/
	public static native String generateImei(String packName, String imei,
			String ua, String mac, String androidId, String stamp, String guid);


	private String getValue(String value) {
		if (value == null)
			return "";
		else
			return value;
	}


	public boolean saveFile(String path, String name, byte[] data) {
		if (data != null && data.length > 0) {
			FileOutputStream fos = null;
			File file = null;
			try {
				File iMochaPath = new File(path);
				if (!iMochaPath.exists()) {
					iMochaPath.mkdirs();
				}
				file = new File(path, name);
				if (file.exists()) {
					return true;
				}
				file.createNewFile();
				fos = new FileOutputStream(file);
				fos.write(data);
			} catch (Exception ex) {
				return false;
			} finally {
				if (fos != null) {
					try {
						fos.close();
					} catch (Exception ex) {
						return false;
					}
				}
			}
			return true;
		}
		return false;
	}

	/*------ ran.huang 2012-12-10 下午6:03:52 add end ------*/

	

}
